import React, { FC } from 'react';
import { Spin, Layout, Button } from 'antd';
import axios from 'axios';
import { Utils } from 'lfun-bg-comp';
import qs from 'qs';
import { WarningOutlined } from '@ant-design/icons';
import { useParams } from 'react-router-dom';

const Groups: FC = () => {
  const res: any = qs.parse(window.location.search?.split('?')[1]);
  const [hasRelogin, setasRelogin] = React.useState(false);
  const params = useParams();
  React.useEffect(() => {
    if (res?.refer_uri && res?.code && res?.state) {
      axios
        .create({
          baseURL: Utils.getProps('srvUrl'),
          headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'X-TENANT-CODE':  `${params.code}`,
          },
          timeout: 30000,
          withCredentials: true,
        })
        .post(Utils.getProps('getTokenUrl'), { code: res.code, state: res.state })
        .then(r => {
          localStorage.setItem('x-mg-token', r?.data?.token);
          window.location.href = decodeURIComponent(decodeURIComponent(res.refer_uri));
        })
        .catch(r => {
          setasRelogin(true);
          console.log(r);
        });
    } else {
      window.location.href = res?.refer_uri || '';
    }
  }, []);
  return (
    <>
      <Layout>
        <Layout.Content style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
          {!hasRelogin ? (
            <Spin tip="Loading..." />
          ) : (
            <>
              <div style={{ fontSize: '68px', color: 'red', display: 'block' }}>
                <WarningOutlined />
              </div>
              <div>
                登录失败，请重新登录
                <Button
                  type="link"
                  onClick={() => {
                    window.location.href = '/';
                  }}
                >
                  重新登录
                </Button>
              </div>
            </>
          )}
        </Layout.Content>
      </Layout>
    </>
  );
};

export default Groups;
